<?php

namespace Xin\LaravelFortify\Model;


use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException as BaseValidationException;
use Xin\LaravelFortify\Validation\ValidationException;

trait FieldValueMutator
{


	/**
	 * 设置当前实例字段值
	 * @param string $field
	 * @param mixed $value
	 * @return bool
	 * @throws BaseValidationException
	 * @deprecated 使用 Service
	 */
	public function setValue($field, $value)
	{
		if (!static::isAllowSetField($field)) {
			throw ValidationException::withMessages([
				'default' => "{$field} not in allow field list.",
			]);
		}

		// 验证规则
		$allowSetFields = static::getAllowSetFields();
		if (isset($allowSetFields[$field]) && ($validateRule = $allowSetFields[$field])) {
			Validator::validate([
				$field => $value,
			], [
				$field => $validateRule,
			]);
		}

		return $this->save([$field => $value]);
	}

	/**
	 * 设置多条记录字段值
	 * @param array|callable $idsOrCallback
	 * @param string $field
	 * @param mixed $value
	 * @throws BaseValidationException
	 * @deprecated 使用 Service
	 */
	public static function setManyValue($idsOrCallback, $field, $value, $itemCallback = null)
	{
		return self::simple()->where(is_array($idsOrCallback) ? [
			['id', 'IN', $idsOrCallback],
		] : $idsOrCallback)->select()->each(function (self $item) use ($field, $value, $itemCallback) {
			$flag = $item->setValue($field, $value);
			if ($itemCallback) {
				$itemCallback($flag);
			}
		});
	}

	/**
	 * 是否允许设置字段
	 *
	 * @param string $field
	 * @return bool
	 * @deprecated 使用 Service
	 */
	public static function isAllowSetField($field)
	{
		$allowSetFields = static::getAllowSetFields();

		return in_array($field, array_map('strval', array_keys($allowSetFields)), true);
	}

	/**
	 * 获取允许修改字段
	 *
	 * @return array
	 * @deprecated 使用 Service
	 */
	public static function getAllowSetFields()
	{
		return [
			'status' => 'in:1,2',
		];
	}
}
